//
//  VehicleListViewController.m
//  阿帕
//
//  Created 阿帕 on 2019/12/25.
//  Copyright © 2019 GCY. All rights reserved.
//

#import "VehicleListViewController.h"

#import "VehicleManageCell.h"

#import "VechicleQrCodeViewController.h"

#import "AddVehicleVC.h"

@interface VehicleListViewController ()<UITableViewDelegate, UITableViewDataSource, VehicleManageListButtonDelegate>

@property (strong , nonatomic)UITextField *textFiled;

@property (strong , nonatomic)UITableView *tableView;

@property (strong , nonatomic)NSMutableArray *dataArray;

@property (strong , nonatomic)UIImageView *foundImageView;

@property (strong , nonatomic)UIButton *confirmButton;

@property (nonatomic, assign) NSInteger pageNum;

@end

@implementation VehicleListViewController

static const CGFloat cellHeight = 130;

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self getVehicleListRequest];
    
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _pageNum = 1;
    
    [self baseViewSetup];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)baseViewSetup {
    
    self.navigationItem.title = @"车辆管理";
    
    self.view.backgroundColor = BackgroundColor;
    
    _textFiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 10, ScreenW, 40)];
    _textFiled.font = font(14);
    _textFiled.text = @"";
    _textFiled.backgroundColor = [UIColor whiteColor];
    _textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textFiled.keyboardType = UIKeyboardTypeDefault;
    _textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"车辆牌照号" attributes:@{NSForegroundColorAttributeName: Light_TextColor}];
    _textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 15, 40)];
    _textFiled.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, 40)];
    _textFiled.leftViewMode = UITextFieldViewModeAlways;
    [_textFiled addSubview: leftView];
    
    
    UIImageView *searchImage = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenW-40, 10, 20, 20)];
    searchImage.userInteractionEnabled = YES;
    searchImage.image = [UIImage imageNamed:@"gcy_icon_search_siji"];
    _textFiled.rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    _textFiled.rightViewMode = UITextFieldViewModeAlways;
    
    [searchImage nyl_addTapGes:^{
        _pageNum = 1;
        [self getVehicleListRequest];
    }];
    
    [_textFiled addSubview:searchImage];
    
    [self.view addSubview:_textFiled];
    
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.confirmButton];
}

- (void)getVehicleListRequest {
    WEAKSELF
    
    if (_pageNum == 1) {
        [self.dataArray removeAllObjects];
    }
    
    NSDictionary *pamars;
    
    if (_isCanBindVehicle == 1) {
        pamars = @{
//            @"code": _driverCode,
            @"licenseNumber": _textFiled.text,
            @"pageSize":DEFULT_LOAD_NUM,
            @"pageNum":[NSNumber numberWithInteger:_pageNum],
            @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
        };
    } else {
        pamars = @{
            @"licenseNumber": _textFiled.text,
            @"pageSize":DEFULT_LOAD_NUM,
            @"pageNum":[NSNumber numberWithInteger:_pageNum],
            @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
        };
    }
    
    
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], VEHICLE_BINDLIST) withParameter:pamars withVC:self netName:@"车辆列表" success:^(id response, NSString *msg) {
        
        if ([response[@"records"] count] != 0) {
            
            [weakSelf.dataArray addObjectsFromArray:[VehicleListModel mj_objectArrayWithKeyValuesArray:response[@"records"]]];
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
            
            weakSelf.foundImageView.hidden = YES;
            weakSelf.tableView.hidden = NO;
            
        }else{
            if (_pageNum == 1) {
                weakSelf.foundImageView.hidden = NO;
                weakSelf.tableView.hidden = YES;
            }
            
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            
        }
        
        [weakSelf.tableView reloadData];
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

- (void)confirmButtonClick {
    
//    VechicleAddViewController *vavc = [[VechicleAddViewController alloc] init];
//    vavc.addType = 0;
//    [self.navigationController pushViewController:vavc animated:YES];
    
    AddVehicleVC *vavc = [[AddVehicleVC alloc] init];
    vavc.addType = 0;
    [self.navigationController pushViewController:vavc animated:YES];
    
}

#pragma mark - VehicleManageListButtonDelegate
- (void)cellButtonIndexClick:(NSInteger)index withButton:(UIButton *)button {
    
    WEAKSELF
    NSIndexPath *indexpath = [self.tableView indexPathForRowAtPoint:[self.tableView convertPoint:button.center fromView:button.superview]];
    NSLog(@"点击了第%ld个item的第%ld个按钮",(long)indexpath.row, (index-99));
    
    VehicleListModel *model = self.dataArray[indexpath.row];
    
    NSString *title = button.titleLabel.text;
    
    if ([title isEqual:@"冻结"]) {
        [DCSpeedy dc_SetUpAlterWithView:self Title:@"" Message:@"确定要冻结车辆吗？" Sure:^{
            
            NSDictionary *params = @{@"code": model.code,@"token":[UserDefaultUtil valueForKey:USER_TOKEN],};
            
            [HTTPManager postNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], VEHICLE_FREEZE) withParameter:params withVC:self netName:@"冻结车辆" success:^(id response, NSString *msg) {
                
                [XSInfoView showInfo:msg onView:weakSelf.view];
                
                VehicleManageCell *cell  = [weakSelf.tableView cellForRowAtIndexPath:indexpath];
                
                cell.model.isFreeze = 1;
                
                [weakSelf.tableView reloadRow:indexpath.row inSection:0 withRowAnimation:UITableViewRowAnimationAutomatic];
                
                
            } failure:^(NSInteger code, NSString *msg) {
                
            }];
            
        } Cancel:^{
            
        }];
        
    } else if ([title isEqual:@"解冻"]) {
        
        [DCSpeedy dc_SetUpAlterWithView:self Title:@"" Message:@"确定要解冻车辆吗？" Sure:^{
            
            NSDictionary *params = @{@"code": model.code,@"token":[UserDefaultUtil valueForKey:USER_TOKEN],};
            
            [HTTPManager postNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], VEHICLE_UNFREEZE) withParameter:params withVC:self netName:@"解冻车辆" success:^(id response, NSString *msg) {
                
                [XSInfoView showInfo:msg onView:weakSelf.view];
                
                VehicleManageCell *cell  = [weakSelf.tableView cellForRowAtIndexPath:indexpath];
                
                cell.model.isFreeze = 0;
                
                [weakSelf.tableView reloadRow:indexpath.row inSection:0 withRowAnimation:UITableViewRowAnimationAutomatic];
                
                
            } failure:^(NSInteger code, NSString *msg) {
                
            }];
            
        } Cancel:^{
            
        }];
        
        
    } else if ([title isEqual:@"编辑"]) {
        
//        VechicleAddViewController *vavc = [[VechicleAddViewController alloc] init];
//        vavc.code = model.code;
//        vavc.addType = 1;
//        [self.navigationController pushViewController:vavc animated:YES];
        if (model.authStatusExt == 3) {
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil message:@"审核成功的车辆不能编辑" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction* action = [UIAlertAction actionWithTitle:@"知道啦" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
               
            }];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            AddVehicleVC *vavc = [[AddVehicleVC alloc] init];
            vavc.code = model.code;
            vavc.addType = 1;
            [self.navigationController pushViewController:vavc animated:YES];
        }
        
    } else if ([title isEqual:@"删除"]) {
        
        [DCSpeedy dc_SetUpAlterWithView:self Title:@"" Message:@"确定要删除车辆吗？" Sure:^{
            
            NSDictionary *params = @{@"code": model.code,@"token":[UserDefaultUtil valueForKey:USER_TOKEN],};
            
            [HTTPManager deleteNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], VEHICLE_DEL) withParameter:params withVC:self netName:@"删除车辆" success:^(id response, NSString *msg) {
                
                [XSInfoView showInfo:@"删除车辆成功" onView:weakSelf.view];
                
                [weakSelf.dataArray removeObjectAtIndex:indexpath.row];
                [weakSelf.tableView deleteRowsAtIndexPaths:@[indexpath] withRowAnimation:UITableViewRowAnimationAutomatic];
                
            } failure:^(NSInteger code, NSString *msg) {
                
            }];
            
        } Cancel:^{
            
        }];
        
    } else if ([title isEqual:@"车辆码"]) {
        
        VechicleQrCodeViewController *vqvc = [[VechicleQrCodeViewController alloc] init];
        vqvc.qrCodeUrl = model.qrCode;
        vqvc.carNumString = model.licenseNumber;
        [self.navigationController pushViewController:vqvc animated:YES];
    }
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    VehicleManageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.delegate = self;
    
    if ([DCSpeedy isBlankArr:self.dataArray] == NO) {
        cell.model = self.dataArray[indexPath.row];
    }
    
    return cell;
}

//上拉刷新数据
- (void)loadNewData{
    _pageNum = 1;
    [self getVehicleListRequest];
}
- (void)loadMoreData{
    _pageNum ++;
    [self getVehicleListRequest];
}


#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return cellHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WEAKSELF
    if (_isCanBindVehicle == 1) {
        VehicleListModel *model = self.dataArray[indexPath.row];
        
        [DCSpeedy dc_SetUpAlterWithView:self Title:@"" Message:CJStringWithFormat(@"是否将%@与车辆%@绑定在一起吗？",_driverName,model.licenseNumber) Sure:^{
            
            NSDictionary *params = @{@"partyCode": _partyCode,
                                     @"vehicleCode": model.code,
                                     @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
            };
            
            [HTTPManager postNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], DRIVER_BINDVEHICLE) withParameter:params withVC:self netName:@"绑定车辆" success:^(id response, NSString *msg) {
                
                [XSInfoView showInfo:@"绑定成功" onView:weakSelf.view];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
                
                
            } failure:^(NSInteger code, NSString *msg) {
                
            }];
            
        } Cancel:^{
            
        }];
    }
    
}
#pragma mark - LazyLoad
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.frame = CGRectMake(0, 51, ScreenW, ScreenH - NavHeight - 51 - 75);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        //注册单元格
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([VehicleManageCell class]) bundle:nil] forCellReuseIdentifier:@"CellID"];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
- (UIImageView *)foundImageView {
    if (!_foundImageView) {
        _foundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 170, 170)];
        _foundImageView.image = image(@"gcy_img_list_found");
        _foundImageView.contentMode = UIViewContentModeScaleAspectFit;
        _foundImageView.center = self.view.center;
        _foundImageView.cy_centerY -=70;
        [self.view addSubview:_foundImageView];
    }
    return _foundImageView;
}

- (UIButton *)confirmButton {
    if (!_confirmButton) {
        _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_confirmButton setTitle:@"新增车辆" forState:UIControlStateNormal];
        [_confirmButton setBackgroundColor:Theme_ColorValue];
        cut(_confirmButton, BTN_BORDER_RADIUS);
        [_confirmButton addTarget:self action:@selector(confirmButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [_confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _confirmButton.frame = CGRectMake(20, ScreenH - NavHeight - 65, ScreenW-40, 45);
    }
    return _confirmButton;
}
@end
